package com.gjy.util;

import java.util.concurrent.*;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-18 10:34:40
 */
public class ThreadUtil {

    public static final Integer processor = Runtime.getRuntime().availableProcessors();

    public static ThreadPoolExecutor defaultPool() {
        return new ThreadPoolExecutor(
                processor
                , processor * 2
                , 1
                , TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(processor * 10)
                , Executors.defaultThreadFactory()
                , new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    public static ThreadPoolExecutor defaultPool(RejectedExecutionHandler rejected) {
        return new ThreadPoolExecutor(
                processor
                , processor * 2
                , 3
                , TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(processor * 10)
                , Executors.defaultThreadFactory()
                , rejected
        );
    }

    public static class ToQueueRejected implements RejectedExecutionHandler {

        private final BlockingQueue<Runnable> queue;

        public ToQueueRejected(BlockingQueue<Runnable> queue) {
            this.queue = queue;
        }

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            if (!executor.isShutdown()) {
                queue.add(r);
            }
        }
    }
}
